﻿using System.Configuration;
using Common.BaseLibrary;
//using Common.BaseLibrary.CachingDataSet;
using Common.BaseLibrary.Caching;
using Common.BaseLibrary.Config;
using Common.BaseLibrary.CQRS;
using Common.BaseLibrary.Domain;
using Common.BaseLibrary.FastDFS;
using Common.BaseLibrary.FastDFS.Common;
using Common.BaseLibrary.Repositories;
using Common.BaseLibrary.Utils;
using Common.BaseLibrary.Utils.Encryptor;
using Common.Repositories.XML;
using Microsoft.Practices.Unity;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;

namespace Solution.Test
{
    class Program
    {
        //static int FaildCount = 0;
        //static int MaxFaildCount = 5;
        //static string DFSGroupName = "tsingda";
        //static int bufferSize = 1024 * 10;


        static void Main(string[] args)
        {
            //Console.WriteLine("-----------------------------------------------");
            //var fileName = "M00/00/00/wKgCMlGkFyGASOCUAAMJ-PUDjH8009.mp4";

            //List<IPEndPoint> trackerIPs = new List<IPEndPoint>();
            //IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 22122);
            //trackerIPs.Add(endPoint);
            //ConnectionManager.Initialize(trackerIPs);
            //StorageNode node = FastDFSClient.GetStorageNode("fdfsgroup1");

            ////===========================UploadFile=====================================
            //byte[] content = null;
            //if (File.Exists(@"c:\resource\video.mp4"))
            //{
            //    FileStream streamUpload = new FileStream(@"c:\resource\video.mp4", FileMode.Open);
            //    using (BinaryReader reader = new BinaryReader(streamUpload))
            //    {
            //        content = reader.ReadBytes((int)streamUpload.Length);
            //    }
            //}
            ////string fileName = FastDFSClient.UploadAppenderFile(node, content, "mdb");
            //fileName = FastDFSClient.UploadFile(node, content, "mp4");

            //===========================BatchUploadFile=====================================
            //string[] _FileEntries = Directory.GetFiles(@"E:\fastimage\三维", "*.jpg");
            //DateTime start = DateTime.Now;
            //foreach (string file in _FileEntries)
            //{
            //    string name = Path.GetFileName(file);
            //    content = null;
            //    FileStream streamUpload = new FileStream(file, FileMode.Open);
            //    using (BinaryReader reader = new BinaryReader(streamUpload))
            //    {
            //        content = reader.ReadBytes((int)streamUpload.Length);
            //    }
            //    //string fileName = FastDFSClient.UploadAppenderFile(node, content, "mdb");
            //    fileName = FastDFSClient.UploadFile(node, content, "jpg");
            //}
            //DateTime end = DateTime.Now;
            //TimeSpan consume = ((TimeSpan)(end - start));
            //double consumeSeconds = Math.Ceiling(consume.TotalSeconds);


            ////===========================Http测试，流读取=======================================
            ////string url = "http://img13.360buyimg.com/da/g5/M02/0D/16/rBEDik_nOJ0IAAAAAAA_cbJCY-UAACrRgMhVLEAAD-J352.jpg";
            ////System.Net.HttpWebRequest req = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(url);
            ////System.Net.HttpWebResponse res = (System.Net.HttpWebResponse)req.GetResponse();
            ////Image myImage = Image.FromStream(res.GetResponseStream());
            ////myImage.Save("c:\\fast.jpg");//保存
            ////===========================Http测试，直接下载=======================================
            //WebClient web = new WebClient();
            //web.DownloadFile("http://img13.360buyimg.com/da/g5/M02/0D/16/rBEDik_nOJ0IAAAAAAA_cbJCY-UAACrRgMhVLEAAD-J352.jpg", "C:\\abc.jpg");
            //web.DownloadFile("http://192.168.81.233/gruop1/M00/00/00/wKhR6VADbNr5s7ODAAIOGO1_YmA574.jpg", "C:\\abc.jpg");

            //Console.WriteLine("Complete");
            //Console.Read();

            #region 上传
            //byte[] content = null;
            //if (File.Exists(@"e:\Abc.wmv"))
            //{
            //    FileStream streamUpload = new FileStream(@"e:\Abc.wmv", FileMode.Open);
            //    using (BinaryReader reader = new BinaryReader(streamUpload))
            //    {
            //        content = reader.ReadBytes((int)streamUpload.Length);//5*1024*1024byte
            //    }
            //}
            ////string fileName = FastDFSClient.UploadAppenderFile(node, content, "mdb");
            //var fileName = FastDFSClient.UploadFile(FastDFSClient.GetStorageNode("tsingda"), content, "wmv", null, (name) =>
            //{
            //    Console.WriteLine(name);
            //});

            #endregion

            //Console.WriteLine("-----------------------------------------------");


            #region 分块上传
            //content = new byte[bufferSize];
            //var streamUp = new FileStream(@"d:\video.mp4", FileMode.Open);
            //streamUp.Read(content, 0, bufferSize);
            //string shortName = FastDFSClient.UploadAppenderFile(FastDFSClient.GetStorageNode(DFSGroupName), content, "mp4");
            //BeginUploadPart(streamUp, shortName);
            //streamUp.Close();
            #endregion

            #region 下载
            //byte[] buffer1 = FastDFSClient.DownloadFile(FastDFSClient.GetStorageNode("tsingda"), fileName, 0L, 0L);
            //var streamDown = new FileStream(@"D:\down.mp4", FileMode.Create);
            //using (BinaryWriter write = new BinaryWriter(streamDown, Encoding.BigEndianUnicode))
            //{
            //    write.Write(buffer1);
            //    write.Close();
            //}
            //streamDown.Close();
            #endregion



            //Logger.LoggerFactory.Instance.Logger_Info("asaa");

            //CacheManager.Instance.Put("key01", "1243");

            ////object obj = CacheManager.Instance.Get("key01");
            //CacheManager.Instance.Put("key01", "1243");


            //object obj= CacheManager.Instance.Get("key01");

            //Console.WriteLine(obj.ToString());

            ////Console.WriteLine(obj);

            //IPExt.EnableFileWatch = true;
            //IPExt.Load("ipdb.dat");


            //Console.WriteLine(String.Join(", ", IPExt.Find("8.8.8.8")));
            //Console.WriteLine(ComputerInfoManager.Instance.GetClientIp());
            //string str= ComputerInfoManager.Instance.GetUserHostIP();
            //Console.WriteLine(str);
            //Console.WriteLine(String.Join(", ", IpManager.Instance.Find(ComputerInfoManager.Instance.GetUserHostIPV4())));


            //Console.WriteLine(Enum.GetName(typeof(WeatherCityCode), 101010100));
            //Array arr = Enum.GetValues(typeof(WeatherCityCode));
            //Console.WriteLine(GetEnumValue(typeof(WeatherCityCode), "北京"));
            //Console.WriteLine(TestWebApiGetAll().Result);
            //Console.WriteLine( IpManager.Instance.Find("13.94.46.118")[1]);
            //Console.ReadKey(true);
            //XmlRepository<City> re = new XmlRepository<City>(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, 
            //"WeatherConfig"));
            //WeatherCityModel model = new WeatherCityModel();

            //var list= re.GetModel();

            //DataSet ds = ConvertXMLFileToDataSet(Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
            // "WeatherConfig.xml"));


            //Console.WriteLine();



            //bool res = ComputerInfoHelper.Instance.ImpersonateValidUser("6992580", "BJ", "Pass123.");
            //Console.WriteLine(res);


            //string temp = ConfigurationManager.AppSettings["UpLoadPath"] + @"\Monthly\Templete.doc";
            //WordHelper.Instance.WordReplace(temp, "（一）项目进展", "aaaa");

            Console.WriteLine(Utility.EncryptString("Bjhg8888",Utility.EncryptorType.SHA256));

        }

        //将xml文件转换为DataSet
        public static DataSet ConvertXMLFileToDataSet(string xmlFile)
        {
            StringReader stream = null;
            XmlTextReader reader = null;
            try
            {
                XmlDocument xmld = new XmlDocument();
                xmld.Load(xmlFile);

                DataSet xmlDS = new DataSet();
                stream = new StringReader(xmld.InnerXml);
                //从stream装载到XmlTextReader
                reader = new XmlTextReader(stream);
                xmlDS.ReadXml(reader);
                //xmlDS.ReadXml(xmlFile);
                return xmlDS;
            }
            catch (System.Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (reader != null) reader.Close();
            }
        }
        public static int GetEnumValue(Type enumType, string enumName)
        {
            try
            {
                if (!enumType.IsEnum)
                    throw new ArgumentException("enumType必须是枚举类型");
                var values = Enum.GetValues(enumType);
                var ht = new Hashtable();
                foreach (var val in values)
                {
                    ht.Add(Enum.GetName(enumType, val), val);
                }
                return (int)ht[enumName];
            }
            catch (Exception e)
            {
                throw e;
            }
        }

    }

    [Serializable]
    public class UserCommandHandler :
        ICommandHandler<AddUserCommand>,
        ICommandHandler<EditUserCommand>,
        ICommandHandler<DelUserCommand>
    {
        #region ICommandHandler<DelUserCommand> 成员

        public void Execute(DelUserCommand command)
        {
            Console.WriteLine(DateTime.Now + "删除" + command.UserID);
        }

        #endregion

        #region ICommandHandler<EditUserCommand> 成员

        public void Execute(EditUserCommand command)
        {
            //TestCFContext db = new TestCFContext();
            //var aggregate = db.Set<TestUser>().Find(command.UserID);
            //if (!string.IsNullOrWhiteSpace(command.UserName))
            //    aggregate.ChangeUserName(command.UserName);
            //if (!string.IsNullOrWhiteSpace(command.Email))
            //    aggregate.ChangeEmail(command.Email);
            //Console.WriteLine(DateTime.Now + "编辑" + command.UserName);
        }

        #endregion

        #region ICommandHandler<AddUserCommand> 成员

        public void Execute(AddUserCommand command)
        {
            Console.WriteLine(DateTime.Now + "添加" + command.UserName);
        }

        #endregion
    }

    #region 命令
    public class AddUserCommand : Command
    {
        public string UserName { get; set; }
        public string Email { get; set; }
    }

    public class EditUserCommand : Command
    {
        public int UserID { get; set; }
        public string UserName { get; set; }
        public string Email { get; set; }
    }

    public class DelUserCommand : Command
    {
        public int UserID { get; set; }
    }
    #endregion

}
